<?php
/**
 * User: aka
 * Date: 2018/6/24
 * Time: 15:22
 */

namespace app\backstage\controller;

use app\common\request\RequestOperation;
use think\Session;

class User
{
    static private $key = '2P8';

    public $requestOperation;
    public $userModel;

    public function __construct()
    {
        $this->requestOperation = new RequestOperation();
        $this->userModel = new \app\backstage\model\User();
    }

    public function __destruct()
    {
        unset($this->requestOperation);
        unset($this->userModel);
    }

    private function getRequestOperation() : RequestOperation
    {
        return $this->requestOperation;
    }

    private function getUserModel() : \app\backstage\model\User
    {
        return $this->userModel;
    }

    public function loginView()
    {
        return view('login');
    }

    public function getToken()
    {
        $key = $this->getRequestOperation()->getAllRequestParam();
        $result = $key['key'] == self::$key;
        $result ?
            $this->getRequestOperation()->getToken()
            :
            $this->getRequestOperation()->errorCodeToJson(500);
    }

    public function loginAction()
    {
        $requestData = $this->getRequestOperation()->getAllRequestParam();
        $requestData['login_ip'] = $this->getRequestOperation()->getUserIp();
        $this->getRequestOperation()->requestValidate('UserLogin',$requestData);
        $result = $this->getUserModel()->login($requestData);
        $result ?
            $this->getRequestOperation()->successCodeToJson(200)
            :
            $this->getRequestOperation()->errorCodeToJson(500);
    }

    public function loginOutAction()
    {
        Session::delete('user');
    }
}